<template>
  <basic-container>
    <el-descriptions title="产品详情" :column="3" size="default">
      <el-descriptions-item label="产品名称 :">
        {{ productDetail.productName }}
        <el-text type="primary" size="small" class="cursor" @click="viewProduct">查看</el-text>
      </el-descriptions-item>
      <el-descriptions-item label="设备类型 :">
        {{ productDetail.deviceTypeName }}
      </el-descriptions-item>
      <el-descriptions-item label="创建时间 :">
        {{ productDetail.createTime }}
      </el-descriptions-item>
      <el-descriptions-item label="所属品类 :">
        {{ productDetail.categoryNameFull }}
      </el-descriptions-item>
      <el-descriptions-item label="数据状态 :">
        {{ productDetail.statusName }}
      </el-descriptions-item>
      <el-descriptions-item label="动态注册 :">
        {{ productDetail.dynamicRegisterName }}
      </el-descriptions-item>

      <el-descriptions-item label="链接协议 :">
        {{ productDetail.linkProtocolName }}
      </el-descriptions-item>
      <el-descriptions-item label="联网方式 :">
        {{ productDetail.connectModeName }}
      </el-descriptions-item>
      <el-descriptions-item label="数据格式 :">
        {{ productDetail.dataTypeName }}
      </el-descriptions-item>

      <el-descriptions-item label="生产厂商 :">
        {{ productDetail.vendors }}
      </el-descriptions-item>
      <el-descriptions-item label="产品型号 :">
        {{ productDetail.model }}
      </el-descriptions-item>
      <el-descriptions-item label="产品描述 :">
        {{ productDetail.productDesc }}
      </el-descriptions-item>
    </el-descriptions>
    <el-divider/>
    <el-descriptions title="设备详情" :column="3" size="default">
      <el-descriptions-item label="设备名称 :">
        {{ deviceDetail.deviceName }}
        <el-text type="primary" size="small" class="cursor" v-clipboard:copy="this.deviceDetail.deviceName"
                 v-clipboard:success="onCopySuccess">复制
        </el-text>
      </el-descriptions-item>
      <el-descriptions-item label="备注名称 :">
        {{ deviceDetail.deviceNoteName }}
        <el-text type="primary" size="small" class="cursor"  @click="updateDeviceNoteName">编辑</el-text>
      </el-descriptions-item>
      <el-descriptions-item label="认证方式 :">
        -
      </el-descriptions-item>
      <el-descriptions-item label="创建时间 :">
        {{ deviceDetail.createTime }}
      </el-descriptions-item>
      <el-descriptions-item label="激活时间 :">
        {{ deviceDetail.activeTime }}
      </el-descriptions-item>
      <el-descriptions-item label="最后上线时间 :">
        {{ deviceDetail.lastOnlineTime }}
      </el-descriptions-item>
      <el-descriptions-item label="设备状态 :">
        {{ deviceDetail.deviceStatusName }}
      </el-descriptions-item>
      <el-descriptions-item label="启用状态 :">
        {{ deviceDetail.status === 1 ? '启用' : '禁用' }}
      </el-descriptions-item>
      <el-descriptions-item label="实时延时 :">
        <el-text type="primary" size="small" class="cursor">测试</el-text>
      </el-descriptions-item>
    </el-descriptions>
    <el-divider/>
    <el-descriptions title="设备扩展信息" :column="3" size="default">
      <el-descriptions-item label="SDK 语言 :">
        -
      </el-descriptions-item>
      <el-descriptions-item label="版本号 :">
        -
      </el-descriptions-item>
      <el-descriptions-item label="模组商 :">
        -
      </el-descriptions-item>
      <el-descriptions-item label="模组信息 :">
        -
      </el-descriptions-item>
    </el-descriptions>
    <el-divider/>
    <el-descriptions title="标签信息" :column="3" size="default">
      <el-descriptions-item label="标签列表 :">
        <template v-for="(item) in data" :key="item.id">
          <el-tag type="info">{{ item.labelKey }}：{{ item.labelValue }}</el-tag>
          <el-divider direction="vertical"/>
        </template>
        <el-text type="primary" size="small" class="cursor" @click="visible=true">编辑</el-text>
      </el-descriptions-item>
    </el-descriptions>
    <el-dialog v-model="visible" title="设备标签配置" width="800">
      <avue-crud ref="crud"
                 :table-loading="loading"
                 :option="option"
                 :data="data"
                 v-model="form"
                 @row-save="rowSave"
                 @row-update="rowUpdate"
                 @row-del="rowDel"></avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getDetailByName, updateDeviceNoteName} from "@/api/iot/device";
import {getDetailByKey} from "@/api/iot/product";
import {add, getList, remove, update} from "@/api/iot/device/label";
import {validatenull} from "@/utils/validate";

export default {
  name: 'deviceInfo',
  props: {
    productKey: String,
    deviceId: String,
    deviceName: String,
  },
  data() {
    const validateKey = (rule, value, callback) => {
      const regex = /^[a-zA-Z0-9_\-:.@]{4,64}$/;
      const isValid = regex.test(value);
      if (!isValid) {
        callback(new Error('支持英文字母，并可包含数字、下划线（_）、中划线（-）、点号（.）、半角冒号（:）以及特殊字符@，整体长度需控制在4至64个字符之间'));
        return;
      }
      callback();
    };
    const validateValue = (rule, value, callback) => {
      const regex = /^[a-zA-Z0-9_\-:.@]{4,128}$/;
      const isValid = regex.test(value);
      if (!isValid) {
        callback(new Error('支持英文字母，并可包含数字、下划线（_）、中划线（-）、点号（.）、半角冒号（:）以及特殊字符@，整体长度需控制在4至128个字符之间'));
        return;
      }
      callback();
    };
    return {
      productDetail: {},
      deviceDetail: {},
      deviceId: '',
      visible: false,
      loading: false,
      form: {},
      option: {
        addBtn: false,
        addRowBtn: true,
        cellBtn: true,
        menuWidth: 250,
        column: [{
          label: '标签名',
          prop: 'labelKey',
          cell: true,
          rules: [{
            required: true,
            trigger: "change",
            validator: validateKey
          }],
        }, {
          label: '标签值',
          prop: 'labelValue',
          cell: true,
          rules: [{
            required: true,
            trigger: "change",
            validator: validateValue
          }],
        }]
      },
      data: [],
    };
  },
  computed: {},
  watch: {
    $route(to, from) {
      if (to.path !== from.path) {
        this.init();
      }
    },
    deviceId() {
      if (!validatenull(this.deviceId)) {
        this.onLoad();
      }
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      getDetailByName(this.deviceName).then(res => {
        this.deviceDetail = res.data.data;
        this.deviceId = this.deviceDetail.id;
      });
      getDetailByKey(this.productKey).then(res => {
        this.productDetail = res.data.data;
      });
    },
    onCopySuccess() {
      this.$message.success('复制成功');
    },
    updateDeviceNoteName() {
      this.$prompt('请输入新的设备备注名称', '修改', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[a-zA-Z\u4e00-\u9fa5\d_]{4,64}$/,
        inputErrorMessage: '请输入中英文，并可包含数字、下划线（_），长度限制为4至64个字符',
        inputValue: this.deviceDetail.deviceNoteName
      }).then(({value}) => {
        updateDeviceNoteName(this.deviceId, value).then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.init();
        });
      });
    },
    rowSave(row, done, loading) {
      row.deviceId = this.deviceDetail.id;
      add(row).then(res => {
        row.id = res.data.data;
        done(row);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done(row);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row, index, done) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            done(row)
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
    onLoad(params = {}) {
      if (validatenull(this.deviceId)) {
        return;
      }
      this.loading = true;
      getList(this.deviceId).then(res => {
        this.data = res.data.data;
        this.loading = false;
      });
    },
    viewProduct() {
      this.$router.push({
        path: `/iot/product/detail/${this.productKey}/${this.productDetail.id}`,
      });
    },
  }
};
</script>

<style>
.cursor {
  cursor: pointer;
}
.el-descriptions__cell{
  width: 33%;
  display: inline-flex;
}
.el-descriptions__content{
  flex: 1;
}
</style>
